# Import some standard Python networking libraries.
import SocketServer

# Import the shared mapping list so we can determine 
# which SAVOIR session relates to received messages.
from SharedMappingList import SharedMappingList

# Import the SAVOIR interface so that we can send "status" messages to savoir.
from HSVOSavoirInterface import HSVOSavoirInterface

# Import the device interface so that we can parse session IDs from messages.
from HSVODeviceInterface import HSVODeviceInterface

# Import some deployment-specific constants.
from hsvo.constants import SERVICE_ID, BI_MULTISESSION, BI_DEBUG

class HSVODeviceMessageHandler(SocketServer.BaseRequestHandler):
    """
    HSVO Device Message Handler
    
    A customized message handler used to parse device state 
    messages and send them to SAVOIR as HSVO status messages.
    """
    
    def handle(self):
        """
        handle() - This method is bound to the threaded TCP server and is called after a
        connection has been established. The self.request.recv() function allows
        us to receive data, which is then parsed, translated, and sent along
        as an HSVO message to the SAVOIR HTTP server.
        """
        
        # Receive the message and send nothing in return (to detach the socket).
        message = self.request.recv(1024)
        self.request.send('')
        
        # If debugging is enabled, write the received message to the terminal.
        if BI_DEBUG:
            print '\nDevice state message received...'
            print '==== Device State Message =================================\n'
            print message+'\n'
        
        # Get the mapping based on the device's session ID or service 
        # ID (depending on its multi-session capabilities).
        mappingList = SharedMappingList()
        if BI_MULTISESSION:
            mapping = mappingList.getMappingByDeviceSession(
                HSVODeviceInterface.getSessionID(message))
        else:
            mapping = mappingList.getMappingByDeviceSession(SERVICE_ID)
        if mapping == None:
            print 'No mapping with that session ID could be found; ignoring message.'
            return
        
        # Get the device's parameters from the received message.
        deviceParameters = HSVODeviceInterface.getParameters(message)
        if not deviceParameters:
            return
        
        # Send the message to SAVOIR.
        savoir = HSVOSavoirInterface()
        if savoir.sendStatus(mapping.savoir_sessionID, mapping.savoirUser, deviceParameters) and BI_DEBUG:
            print "Sending complete.\n"